import React, { useState, useEffect } from "react";
import {
  Table,
  Card,
  Button,
  Input,
  Space,
  message,
  Popconfirm,
  Tag,
  Avatar,
  Select,
  Dropdown,
  Menu,
} from "antd";
import type { TablePaginationConfig } from "antd/es/table";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  InfoCircleOutlined,
  DownOutlined,
} from "@ant-design/icons";
import type { MenuInfo } from "rc-menu/lib/interface";
import { adminApi } from "../../api/services/admin/admin";
import type { UserListItem, UserListQueryParams } from "../../api/dto/admin";
import AddUserModal from "./AddUserModal";
import EditUserModal from "./EditUserModal";
import "./UserManager.module.less";
const { Search } = Input;
const { Option } = Select;

// 角色映射函数
const getRoleText = (role: number): string => {
  switch (role) {
    case 1:
      return "学生";
    case 2:
      return "老师";
    default:
      return "未知";
  }
};

// 角色颜色映射函数
const getRoleColor = (role: number): string => {
  switch (role) {
    case 1:
      return "green";
    case 2:
      return "blue";
    default:
      return "default";
  }
};

// 状态映射函数
const getStatusText = (status: number): string => {
  switch (status) {
    case 0:
      return "禁用";
    case 1:
      return "启用";
    case 2:
      return "待验证";
    default:
      return "未知";
  }
};

// 状态颜色映射函数
const getStatusColor = (status: number): string => {
  switch (status) {
    case 0:
      return "red";
    case 1:
      return "green";
    case 2:
      return "orange";
    default:
      return "default";
  }
};

const UserManager: React.FC = () => {
  const [users, setUsers] = useState<UserListItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editingUserId, setEditingUserId] = useState<number | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filters, setFilters] = useState({
    systemRole: 0,
    status: 0,
  });

  // 获取用户列表数据
  const fetchUsers = async (params: UserListQueryParams = {}) => {
    setLoading(true);
    try {
      const response = await adminApi.getUserList({
        page: pagination.current,
        pageSize: pagination.pageSize,
        name: searchText || undefined,
        systemRole: filters.systemRole || undefined,
        status: filters.status || undefined,
        sortBy: "createTime",
        sortOrder: "desc",
        ...params,
      });

      if (response.code === 200) {
        setUsers(response.data?.records || []);
        setPagination((prev) => ({
          ...prev,
          total: response.data?.total || 0,
        }));
      } else if (response.code === 500) {
        message.error("获取用户列表失败");
      } else if (response.code === 401) {
        message.error("未授权");
      }
    } catch {
      message.error("获取用户列表失败，请稍后再试");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [pagination.current, pagination.pageSize, searchText, filters]);

  const handleSearch = (value: string) => {
    setSearchText(value);
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

  const handleTableChange = (paginationInfo: TablePaginationConfig) => {
    setPagination((prev) => ({
      ...prev,
      current: paginationInfo.current || 1,
      pageSize: paginationInfo.pageSize || 10,
    }));

    fetchUsers({
      page: paginationInfo.current,
      pageSize: paginationInfo.pageSize,
    });
  };

  const updateUserStatus = async (userId: number, status: number) => {
    try {
      const response = await adminApi.updateUserStatus({
        id: userId.toString(),
        status: status,
      });

      if (response.code === 200) {
        message.success(`用户状态已更新为${getStatusText(status)}`);
        fetchUsers();
      } else {
        message.error(response.message || "状态更新失败");
      }
    } catch (error) {
      console.error("更新用户状态失败:", error);
      message.error("状态更新失败，请稍后再试");
    }
  };

  const handleStatusClick = (userId: number) => (e: MenuInfo) => {
    let newStatus: number;
    switch (e.key) {
      case "1":
        newStatus = 1; // 启用
        break;
      case "2":
        newStatus = 0; // 禁用
        break;
      case "3":
        newStatus = 2; // 待验证
        break;
      default:
        newStatus = 0;
    }
    updateUserStatus(userId, newStatus);
  };

  const handleFilterChange = (key: string, value: string | number) => {
    setFilters((prev) => ({ ...prev, [key]: value }));
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

  const handleAdd = () => {
    setAddModalVisible(true);
  };

  const handleAddSuccess = () => {
    fetchUsers();
  };

  const handleEdit = (record: UserListItem) => {
    setEditingUserId(record.id);
    setEditModalVisible(true);
  };

  const handleEditSuccess = () => {
    fetchUsers();
  };

  const handleDelete = async (userId: number) => {
    try {
      const response = await adminApi.deleteUser(userId.toString());

      if (response.code === 200) {
        message.success("用户删除成功");
      }
      const isLastItemOnPage = users.length === 1 && pagination.current > 1;
      const newCurrentPage = isLastItemOnPage
        ? pagination.current - 1
        : pagination.current;
      setPagination((prev) => ({
        ...prev,
        current: isLastItemOnPage ? prev.current - 1 : prev.current,
      }));

      await fetchUsers({
        page: newCurrentPage,
        pageSize: pagination.pageSize,
      });
    } catch (error) {
      console.error("删除用户失败:", error);
      message.error("删除失败");
    }
  };

  const columns = [
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
      width: 80,
      render: () => <Avatar icon={<UserOutlined />} size={40} />,
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      render: (name: string) => name || "未设置",
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
      render: (username: string) => username || "未设置",
    },
    {
      title: "学号/工号",
      dataIndex: "profileId",
      key: "profileId",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
      render: (email: string) => email || "未设置",
    },
    {
      title: "手机号",
      dataIndex: "phoneNumber",
      key: "phoneNumber",
      render: (phone: string) => phone || "未设置",
    },
    {
      title: "角色",
      dataIndex: "systemRole",
      key: "systemRole",
      render: (role: number) => (
        <Tag color={getRoleColor(role)}>{getRoleText(role)}</Tag>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: number) => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: "操作",
      key: "action",
      width: 200,
      render: (_: unknown, record: UserListItem) => (
        <Space size="middle">
          <Dropdown
            overlay={
              <Menu onClick={handleStatusClick(record.id)}>
                <Menu.Item key="1">
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <CheckCircleOutlined
                      style={{ color: "green", marginRight: 8 }}
                    />
                    <span>启用</span>
                  </div>
                </Menu.Item>
                <Menu.Item key="2">
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <CloseCircleOutlined
                      style={{ color: "red", marginRight: 8 }}
                    />
                    <span>禁用</span>
                  </div>
                </Menu.Item>
                <Menu.Item key="3">
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <InfoCircleOutlined
                      style={{ color: "blue", marginRight: 8 }}
                    />
                    <span>待验证</span>
                  </div>
                </Menu.Item>
              </Menu>
            }
          >
            <Button
              type="link"
              style={{ color: "gray" }}
              icon={<DownOutlined style={{ color: "gray" }} />}
            >
              状态
            </Button>
          </Dropdown>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="user-manager-container">
      <Card className="user-manager-card">
        <div className="search-section flex justify-between items-center pb-[20px] px-[0px]">
          <div className="left">
            <Search
              placeholder="搜索用户姓名、用户名、学号或邮箱"
              allowClear
              enterButton={<SearchOutlined />}
              size="large"
              onSearch={handleSearch}
              style={{ maxWidth: 400, height: 40 }}
            />
          </div>
          <div className="right">
            <Space style={{ marginLeft: 16 }}>
              <Select
                placeholder="选择角色"
                allowClear
                style={{ width: 120, height: 40 }}
                onChange={(value) => handleFilterChange("systemRole", value)}
              >
                <Option value={1}>学生</Option>
                <Option value={2}>老师</Option>
              </Select>

              <Select
                placeholder="选择状态"
                allowClear
                style={{ width: 120, height: 40, marginRight: 10 }}
                onChange={(value) => handleFilterChange("status", value)}
              >
                <Option value={0}>禁用</Option>
                <Option value={1}>启用</Option>
                <Option value={2}>待验证</Option>
              </Select>
            </Space>
            <Button
              type="primary"
              style={{
                width: 120,
                height: 40,
              }}
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加用户
            </Button>
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ["10", "20", "50", "100"],
          }}
          onChange={handleTableChange}
          className="user-table"
        />
      </Card>

      {/* 添加用户弹窗 */}
      <AddUserModal
        open={addModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onSuccess={handleAddSuccess}
      />

      {/* 编辑用户弹窗 */}
      <EditUserModal
        open={editModalVisible}
        userId={editingUserId}
        onCancel={() => {
          setEditModalVisible(false);
          setEditingUserId(null);
        }}
        onSuccess={handleEditSuccess}
      />
    </div>
  );
};

export default UserManager;
